package com.quiz.bis.service.impl;

import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * 图片哈希服务
 */
@Service
public class ImageHashService {

    /**
     * 计算图片的感知哈希
     */
    public String calculatePerceptualHash(String imagePath) {
        try {
            BufferedImage img = ImageIO.read(new File(imagePath));
            return calculatePHash(img);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 比较两个哈希值的相似度
     */
    public double compareHashes(String hash1, String hash2) {
        if (hash1 == null || hash2 == null || hash1.length() != hash2.length()) {
            return 0.0;
        }

        int differences = 0;
        for (int i = 0; i < hash1.length(); i++) {
            if (hash1.charAt(i) != hash2.charAt(i)) {
                differences++;
            }
        }
        return 1.0 - (double) differences / hash1.length();
    }

    /**
     * 计算pHash算法
     */
    private String calculatePHash(BufferedImage img) {
        // 简化版实现，实际中可以使用更复杂的算法
        // 1. 缩小尺寸到8x8
        BufferedImage resized = new BufferedImage(8, 8, BufferedImage.TYPE_BYTE_GRAY);
        resized.getGraphics().drawImage(img.getScaledInstance(8, 8, java.awt.Image.SCALE_SMOOTH), 0, 0, null);

        // 2. 简化色彩为灰度
        int total = 0;
        int[] gray = new int[64];
        for (int y = 0; y < 8; y++) {
            for (int x = 0; x < 8; x++) {
                int rgb = resized.getRGB(x, y);
                int r = (rgb >> 16) & 0xff;
                int g = (rgb >> 8) & 0xff;
                int b = rgb & 0xff;
                gray[y * 8 + x] = (r + g + b) / 3;
                total += gray[y * 8 + x];
            }
        }

        // 3. 计算平均值
        int average = total / 64;

        // 4. 比较像素的灰度
        StringBuilder hash = new StringBuilder();
        for (int value : gray) {
            hash.append(value > average ? "1" : "0");
        }

        return hash.toString();
    }
}